package com.feiyi.app.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.feiyi.app.R;
import com.feiyi.app.activity.SubmitOrderActivity;
import com.feiyi.app.adapter.shoppingcart.ShopcartExpandableListViewAdapter;
import com.feiyi.app.app.AppConstant;
import com.feiyi.app.base.BaseActivity;
import com.feiyi.app.base.BaseFragment;
import com.feiyi.app.bean.CartListBean;
import com.feiyi.app.bean.UpdateCartBean;
import com.feiyi.app.bean.shoppingcart.GroupInfo;
import com.feiyi.app.bean.shoppingcart.ProductInfo;
import com.feiyi.app.net.HttpMethods;
import com.feiyi.app.view.shoppingcart.SuperExpandableListView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * 作者 : wlt
 * 创建时间:  2018-07-14
 * QQ : 1346947404
 * 邮箱:wanglt_android@163.com
 * 类说明:购物车界面
 * In me the tiger sniffs the rose
 */

public class CartFragment extends BaseFragment implements ShopcartExpandableListViewAdapter.CheckInterface, ShopcartExpandableListViewAdapter.ModifyCountInterface, View.OnClickListener ,OnRefreshListener {

    private SuperExpandableListView exListView;
    private CheckBox cb_check_all;
    private TextView tv_total_price;
    private TextView tv_delete;
    private TextView tv_go_to_pay;
    private Context context;
    private ImageView iv_empty;
    private LinearLayout ll_pay;
    private TextView tv_empty;
    private TextView tv_empty_2;
    /**
     * 增加购物车的刷新控件
     */
    private SmartRefreshLayout refreshLayout;
    private double totalPrice = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量

    private ShopcartExpandableListViewAdapter selva;
    private List<GroupInfo> groups = new ArrayList<GroupInfo>();// 组元素数据列表
    private Map<String, List<ProductInfo>> children = new HashMap<>();// 子元素数据列表
    private View view;

    private CartListBean cartListBeanLocal;
   public AlertDialog alert;
    public static final String ALIPAY_SHOP = "https://qr.alipay.com/stx05107r5oaa4fyofbkh24";//商户
    public static final String ALIPAY_PERSON = "HTTPS://QR.ALIPAY.COM/FKX06148QMZIJDXGPKXXE7";//个人(支付宝里面我的二维码)
    public static final String ALIPAY_PERSON_2_PAY = "HTTPS://QR.ALIPAY.COM/FKX01415BIHINQT6TRU53F";//个人(支付宝里面我的二维码,然后提示让用的收款码)
    private String uid;
    private String sid;
    private static final String TAG = "main CartFragment";
    @Override
    public View getLayoutInflater(LayoutInflater inflater) {
        view = inflater.inflate(R.layout.fragment_shooping_cart,null);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void initView() {
        context = activity;
//        virtualData();
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(this);
        exListView = (SuperExpandableListView) view.findViewById(R.id.exListView);
        cb_check_all = (CheckBox) view.findViewById(R.id.all_chekbox);
        tv_total_price = (TextView) view.findViewById(R.id.tv_total_price);
        tv_delete = (TextView) view.findViewById(R.id.tv_delete);
        tv_go_to_pay = (TextView) view.findViewById(R.id.tv_go_to_pay);
        iv_empty = view.findViewById(R.id.iv_empty);
        ll_pay = view.findViewById(R.id.ll_pay);
        tv_empty = view.findViewById(R.id.tv_empty);
        tv_empty_2 = view.findViewById(R.id.tv_empty_2);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        initDate();
        refreshLayout.finishRefresh(500);
    }
    @Subscribe
    public void onCartChanged(String changed){
        initDate();

    }

    @Override
    public void initDate() {

        uid = BaseActivity.spUtils.getString(AppConstant.UID);
        sid = BaseActivity.spUtils.getString(AppConstant.SID);

        FormBody.Builder builder = new FormBody.Builder();
        if (null != sid)
        builder.add("sid",sid);
        if (null != uid)
        builder.add("uid",uid);
        RequestBody body = builder.build();
        HttpMethods.getInstance().info.getCartList(AppConstant.CART_LIST_URL,body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CartListBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(CartListBean cartListBean) {
                        Log.e("main", "onNext: "+cartListBean.toString() );
                        if (cartListBean.getStatus().getSucceed() == 1){
                            iv_empty.setVisibility(View.GONE);
                            tv_empty.setVisibility(View.GONE);
                            tv_empty_2.setVisibility(View.GONE);
                            ll_pay.setVisibility(View.VISIBLE);
                            cartListBeanLocal = cartListBean;
                            virtualData();
                        }else {

                            iv_empty.setVisibility(View.VISIBLE);
                            tv_empty.setVisibility(View.VISIBLE);
                            tv_empty_2.setVisibility(View.VISIBLE);
                            ll_pay.setVisibility(View.GONE);

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @Override
    public void initAdapter() {
        selva = new ShopcartExpandableListViewAdapter(groups, children, activity);
        selva.setCheckInterface(this);// 关键步骤1,设置复选框接口
        selva.setModifyCountInterface(this);// 关键步骤2,设置数量增减接口
        exListView.setAdapter(selva);

        for (int i = 0; i < selva.getGroupCount(); i++) {
            exListView.expandGroup(i);// 关键步骤3,初始化时，将ExpandableListView以展开的方式呈现
        }

        cb_check_all.setOnClickListener(this);
        tv_delete.setOnClickListener(this);
        tv_go_to_pay.setOnClickListener(this);
    }


    /**
     * 模拟数据<br>
     * 遵循适配器的数据列表填充原则，组元素被放在一个List中，对应的组元素下辖的子元素被放在Map中，<br>
     * 其键是组元素的Id(通常是一个唯一指定组元素身份的值)
     */
    private void virtualData() {
        if (!groups.isEmpty()){groups.clear();}
        if (null != cartListBeanLocal.getData()){
            groups.add(new GroupInfo(cartListBeanLocal.getData().getShop_list().get(0).getShop_id(),cartListBeanLocal.getData().getShop_list().get(0).getShop_name()));
            List<ProductInfo> products = new ArrayList<>();
            for (int i = 0; i < cartListBeanLocal.getData().getShop_list().get(0).getGoods_list().size(); i++) {
                CartListBean.DataBean.ShopListBean.GoodsListBean bean = cartListBeanLocal.getData().getShop_list().get(0).getGoods_list().get(i);
                double d = cartListBeanLocal.getData().getShop_list().get(0).getGoods_list().get(i).getGoods_price_int();
                int number = bean.getGoods_number();
                products.add(new ProductInfo(bean.getGoods_id(),bean.getGoods_name(),bean.getImg().getThumb(),bean.getGoods_name(),d,number,bean.getRec_id()));
            }
            children.put(groups.get(0).getId(),products);
        }
        for (int i = 0; i < selva.getGroupCount(); i++) {
            exListView.expandGroup(i);// 关键步骤3,初始化时，将ExpandableListView以展开的方式呈现
        }
        selva.notifyDataSetChanged();
    }

    @Override
    public void checkGroup(int groupPosition, boolean isChecked) {
        GroupInfo group = groups.get(groupPosition);
        List<ProductInfo> childs = children.get(group.getId());
        for (int i = 0; i < childs.size(); i++) {
            childs.get(i).setChoosed(isChecked);
        }
        if (isAllCheck())
            cb_check_all.setChecked(true);
        else
            cb_check_all.setChecked(false);
        selva.notifyDataSetChanged();
        calculate();
    }

    @Override
    public void checkChild(int groupPosition, int childPosition, boolean isChecked) {
        boolean allChildSameState = true;// 判断改组下面的所有子元素是否是同一种状态
        GroupInfo group = groups.get(groupPosition);
        List<ProductInfo> childs = children.get(group.getId());
        for (int i = 0; i < childs.size(); i++) {
            if (childs.get(i).isChoosed() != isChecked) {
                allChildSameState = false;
                break;
            }
        }
        if (allChildSameState) {
            group.setChoosed(isChecked);// 如果所有子元素状态相同，那么对应的组元素被设为这种统一状态
        } else {
            group.setChoosed(false);// 否则，组元素一律设置为未选中状态
        }

        if (isAllCheck())
            cb_check_all.setChecked(true);
        else
            cb_check_all.setChecked(false);
        selva.notifyDataSetChanged();
        calculate();
    }

    @Override
    public void doIncrease(int groupPosition, int childPosition, View showCountView, boolean isChecked) {
        ProductInfo product = (ProductInfo) selva.getChild(groupPosition, childPosition);
        int currentCount = product.getCount();
        currentCount++;
        product.setCount(currentCount);
        ((TextView) showCountView).setText(currentCount + "");
        selva.notifyDataSetChanged();
        calculate();
        updateCart(groupPosition,childPosition,showCountView,true);
    }

    @Override
    public void doDecrease(int groupPosition, int childPosition, View showCountView, boolean isChecked) {
        ProductInfo product = (ProductInfo) selva.getChild(groupPosition, childPosition);
        int currentCount = product.getCount();
        if (currentCount == 1)
            return;
        currentCount--;

        product.setCount(currentCount);
        ((TextView) showCountView).setText(currentCount + "");
        selva.notifyDataSetChanged();
        calculate();
        updateCart(groupPosition,childPosition,showCountView,false);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.all_chekbox:
                doCheckAll();
                break;
            case R.id.tv_go_to_pay:
                if (totalCount == 0) {
                    Toast.makeText(context, "请选择要支付的商品", Toast.LENGTH_LONG).show();
                    return;
                }
                String rec_id = "";
                for (int i = 0; i < cartListBeanLocal.getData().getShop_list().size(); i++) {
                    rec_id+=cartListBeanLocal.getData().getShop_list().get(i).getShop_id()+",";
                }
                Bundle bundle = new Bundle();
                bundle.putString("rec_id",rec_id);
                ActivityUtils.startActivity(bundle,getActivity(),SubmitOrderActivity.class);

                break;
            case R.id.tv_delete:
                if (totalCount == 0) {
                    Toast.makeText(context, "请选择要移除的商品", Toast.LENGTH_LONG).show();
                    return;
                }
                alert = new AlertDialog.Builder(context).create();
                alert.setTitle("操作提示");
                alert.setMessage("您确定要将这些商品从购物车中移除吗？");
                alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        return;
                    }
                });
                alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        doDelete();
                    }
                });
                alert.show();
                break;
        }
    }

    /**
     * 删除操作<br>
     * 1.不要边遍历边删除，容易出现数组越界的情况<br>
     * 2.现将要删除的对象放进相应的列表容器中，待遍历完后，以removeAll的方式进行删除
     */
    public void doDelete() {
        List<GroupInfo> toBeDeleteGroups = new ArrayList<GroupInfo>();// 待删除的组元素列表
        for (int i = 0; i < groups.size(); i++) {
            GroupInfo group = groups.get(i);
            if (group.isChoosed()) {

                toBeDeleteGroups.add(group);
            }
            List<ProductInfo> toBeDeleteProducts = new ArrayList<ProductInfo>();// 待删除的子元素列表
            List<ProductInfo> childs = children.get(group.getId());
            for (int j = 0; j < childs.size(); j++) {
                if (childs.get(j).isChoosed()) {
                    toBeDeleteProducts.add(childs.get(j));
                }
            }
            childs.removeAll(toBeDeleteProducts);

        }

        groups.removeAll(toBeDeleteGroups);

        selva.notifyDataSetChanged();
        calculate();
    }

    /** 全选与反选 */
    private void doCheckAll() {
        for (int i = 0; i < groups.size(); i++) {
            groups.get(i).setChoosed(cb_check_all.isChecked());
            GroupInfo group = groups.get(i);
            List<ProductInfo> childs = children.get(group.getId());
            for (int j = 0; j < childs.size(); j++) {
                childs.get(j).setChoosed(cb_check_all.isChecked());
            }
        }
        selva.notifyDataSetChanged();
        calculate();
    }

    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给底部的textView进行数据填充
     */
    private void calculate() {
        totalCount = 0;
        totalPrice = 0.00;
        for (int i = 0; i < groups.size(); i++) {
            GroupInfo group = groups.get(i);
            List<ProductInfo> childs = children.get(group.getId());
            for (int j = 0; j < childs.size(); j++) {
                ProductInfo product = childs.get(j);
                if (product.isChoosed()) {
                    totalCount++;
                    totalPrice += product.getPrice() * product.getCount();
                }
            }
        }
        tv_total_price.setText("￥" + totalPrice);
        tv_go_to_pay.setText("去支付(" + totalCount + ")");
    }

    private boolean isAllCheck() {
        for (GroupInfo group : groups) {
            if (!group.isChoosed())
                return false;
        }
        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        if (alert != null && alert.isShowing()){
            alert.dismiss();
        }
    }

    /***************************************************假的直接隐式intent调用支付宝***********************************************************************************************/

    /**
     * 支付
     *
     * @param qrCode
     */
    private void openAliPay2Pay(String qrCode) {
        if (openAlipayPayPage(activity, qrCode)) {
            Toast.makeText(getActivity(), "跳转成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getActivity(), "跳转失败", Toast.LENGTH_SHORT).show();
        }
    }

    public static boolean openAlipayPayPage(Context context, String qrcode) {
        try {
            qrcode = URLEncoder.encode(qrcode, "utf-8");
        } catch (Exception e) {
        }
        try {
            final String alipayqr = "alipayqr://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=" + qrcode;
            openUri(context, alipayqr + "%3F_s%3Dweb-other&_t=" + System.currentTimeMillis());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 发送一个intent
     *
     * @param context
     * @param s
     */
    private static void openUri(Context context, String s) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(s));
        context.startActivity(intent);
    }

    /**
     * 更新购物车代码,当改变购物车内商品数量的时候调用这个接口通知后台修改数据
     *
     */
    private void updateCart(int groupPosition, int childPosition, final View showCountView, final boolean isAdd){
        uid = BaseActivity.spUtils.getString(AppConstant.UID);
        sid = BaseActivity.spUtils.getString(AppConstant.SID);
        final ProductInfo productInfo = (ProductInfo)selva.getChild(groupPosition,childPosition);
        String rec_id = productInfo.getRec_id();
        final int new_number = productInfo.getCount();
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("sid",sid);
        builder.add("uid",uid);
        builder.add("rec_id",rec_id);
        builder.add("new_number",new_number+"");
        RequestBody body = builder.build();

        HttpMethods.getInstance().info.updateCart(AppConstant.UPDATE_CART,body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UpdateCartBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(UpdateCartBean updateCartBean) {
                        if (updateCartBean.getStatus().getSucceed() == 1){
//                            ToastUtils.showShort("更新购物车成功");
                        }else {
                            ToastUtils.showShort("更新购物车失败"+updateCartBean.getStatus().getError_desc());
                            /**
                             *  int currentCount = product.getCount();
                             currentCount++;
                             product.setCount(currentCount);
                             ((TextView) showCountView).setText(currentCount + "");
                             updateCart(product.getRec_id(),currentCount,showCountView,true);
                             selva.notifyDataSetChanged();
                             calcu
                             */
                            int newCount = 1;
                            if (isAdd){
                               newCount = new_number-1;
                            }else {
                               newCount = new_number+1;
                            }
                            productInfo.setCount(newCount);
                            ((TextView)showCountView).setText(newCount+"");
                            selva.notifyDataSetChanged();
                            calculate();

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: "+e.toString() );
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }
}
